package com.yidu.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>Created with IntelliJ IDEA.</p>
 * <p>User: liandyao</p>
 * <p>Date: 2020-07-29</p>
 * <p>Time: 9:36</p>
 * <p>Description: zuul过滤器</p>
 */
@Component
public class UserFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre"; // 设置过滤器类型为：pre
    }

    @Override
    public int filterOrder() {
        return 0; // 设置执行顺序
    }

    @Override
    public boolean shouldFilter() {
        return true; //过滤器需要执行
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String userName = request.getParameter("name");
        String password = request.getParameter("password");
        if(!"admin".equalsIgnoreCase(userName) || !"123".equals(password)){
            HttpServletResponse response = context.getResponse();
            response.setCharacterEncoding("UTF-8");
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
            context.setResponseBody("Sorry, no access allowed!");
            return null ;
        }
        return null;
    }
}
